const Koa = require('koa')
const path = require('path');
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const staticCache = require("koa-static-cache");
const index = require('./routes/index')
const Loadable = require('react-loadable')

const app = new Koa()

// error handler
onerror(app)

// middlewares
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '../dist'))// error-handling
app.use(staticCache(path.resolve(__dirname, '../build'), {
  maxAge: 365 * 24 * 60 * 60,
  gzip: true
}));

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

//route
app.use(index.routes(), index.allowedMethods())

app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

const port = process.env.PORT || '3008';
Loadable.preloadAll().then(() => {
  app.listen(port, () => {
    console.log('listen on:' + port);
  });
})
